package vip.xiaonuo.modular.manage.tsdatarecord.parser;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import vip.xiaonuo.modular.manage.tsdatarecord.entity.BaseMetadata;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 * ExcelDataListener
 *
 * @author JackLee
 * 2022/8/9 15:14
 */
@Data
public class ExcelDataListener extends AnalysisEventListener<Map<Integer, String>> {

    private int dealSize;

    private String recordId;

    private Consumer<List<BaseMetadata>> consumer;

    private ParserResult parserResult;

    private List<BaseMetadata> cacheList = new ArrayList<>(dealSize);

    private int total = 0;

    private String intoDate = DateUtil.now();

    public ExcelDataListener(int dealSize, String recordId, Consumer<List<BaseMetadata>> consumer, ParserResult parserResult) {
        this.dealSize = dealSize;
        this.recordId = recordId;
        this.consumer = consumer;
        this.parserResult = parserResult;
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        if (MapUtil.isNotEmpty(data)) {
            total++;
            BaseMetadata metadata = new BaseMetadata();
            metadata.setRecordId(recordId);
            metadata.setCreateDate(intoDate);
            Map<String, String> resultMap = new HashMap<>();
            data.forEach((key, value) -> resultMap.put("index" + (key + 1), value));
            metadata.setContent(JSON.toJSONString(resultMap));
            cacheList.add(metadata);
            if (cacheList.size() >= dealSize) {
                consumer.accept(cacheList);
                cacheList = new ArrayList<>(dealSize);
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (cacheList.size() > 0) {
            consumer.accept(cacheList);
        }
        parserResult.setTotalCount(total);
    }


    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        List<TableColumn> tableColumns = new ArrayList<>();
        headMap.entrySet().forEach(e -> {
            TableColumn column = new TableColumn();
            column.setTitle(e.getValue());
            column.setSort(e.getKey() + 1);
            column.setDataIndex("index" + (e.getKey() + 1));
            tableColumns.add(column);
        });
        parserResult.setColumnList(tableColumns);
    }
}
